package com.suxin.algorithm.tree.binary;

/**
 * @author Tang
 * @classname TreePrint
 * @description [ 二叉树遍历方式 ]
 * @date 2022/10/20 13:42
 */
public class TreePrint {

    /**
     * 前序遍历 根 左 右
     */
    public static  <T> void beforePrint(Node<T> root) {
        System.out.print(root.getData());
        if (root.getLeft() != null) {
            beforePrint(root.getLeft());
        }
        if (root.getRight() != null) {
            beforePrint(root.getRight());
        }
    }

    /**
     * 中序遍历 左 根 右
     */
    public static <T> void centerPrint(Node<T> root) {
        if (root.getLeft() != null) {
            centerPrint(root.getLeft());
        }
        System.out.print(root.getData()+"-");
        if (root.getRight() != null) {
            centerPrint(root.getRight());
        }
    }

    /**
     * 后序遍历 左 右 根
     */
    public static <T> void afterPrint(Node<T> root) {
        if (root.getLeft() != null) {
            afterPrint(root.getLeft());
        }
        if (root.getRight() != null) {
            afterPrint(root.getRight());
        }
        System.out.print(root.getData());
    }

    public static void main(String[] args) {
        Node<String> Node4 = new Node<>("D",null,null);
        Node<String> Node3 = new Node<>("C",Node4,null);
        Node<String> Node1 = new Node<>("B",null,Node3);

        Node<String> Node7 = new Node<>("H",null,null);
        Node<String> Node8 = new Node<>("K",null,null);
        Node<String> Node6 = new Node<>("G",Node7,Node8);
        Node<String> Node5 = new Node<>("F",Node6,null);
        Node<String> Node2 = new Node<>("E",null,Node5);

        Node<String> rootNode = new Node<>("A",Node1,Node2);

        System.out.println("前序遍历：");
        beforePrint(rootNode);
        System.out.println();

        System.out.println("中序遍历：");
        centerPrint(rootNode);
        System.out.println();

        System.out.println("后序遍历：");
        afterPrint(rootNode);
        System.out.println();
    }

}